/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wbd_au.browsers;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import wbd_au.DBManager;
import wbd_au.TableColumnAdjuster;
import wbd_au.objects_mappings.ObjectMapping;

/**
 *
 * @author Gospo
 */
public class WybierzJDialog extends javax.swing.JDialog {

    private final JComponent targetOutComponent;
    private final Object[] columns;
    private ArrayList<JComponent> fields;
    private Class targetClass;
    private final ArrayList<Object> conditionColumns;
    private final ArrayList<JLabel> labels;

    /**
     * Creates new form WybierzJDialog
     */
    public WybierzJDialog(java.awt.Frame parent, boolean modal, JComponent outComponent, Object[] columns, ArrayList<JComponent> fields, ArrayList<JLabel> labels, ArrayList<Object> conditionColumns, Class targetClass) {
        super(parent, modal);
        this.columns = columns;
        this.targetOutComponent = outComponent;
        this.fields = fields;
        this.targetClass = targetClass;
        this.conditionColumns = conditionColumns;
        this.labels = labels;
        initComponents();
        myInitComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        wyszukajJButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setModel(new DefaultTableModel(columns, 0));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        wyszukajJButton.setText("Wyszukaj");
        wyszukajJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                wyszukajJButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 134, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 180, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 117, Short.MAX_VALUE)
                        .addComponent(wyszukajJButton)
                        .addGap(60, 60, 60))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(wyszukajJButton))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void wyszukajJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wyszukajJButtonActionPerformed
        try {
            ObjectMapping auxObjectMapping = (ObjectMapping) targetClass.getConstructor().newInstance();

            String tableName = auxObjectMapping.getTableName();
            String whereCondition = buildWhereCondition();
            String query = "select "
                    + auxObjectMapping.getAttrSelectList()
                    + " from " + tableName + " where " + whereCondition;
            Statement stmt = DBManager.con.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            // --- clear table
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
            model.getDataVector().removeAllElements();
            model.fireTableDataChanged();
            // ---
            while (rs.next()) {
                ObjectMapping objectMapping = (ObjectMapping) auxObjectMapping.read(rs);
                ObjectMapping.addToTable(objectMapping, jTable1);
            }
        } catch (Exception ex) {
            Logger.getLogger(WybierzJDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_wyszukajJButtonActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        final int idColumn = 0;
        int selectedRow = jTable1.getSelectedRow();
        Object valueAt = jTable1.getValueAt(selectedRow, idColumn);
        if (valueAt != null && targetOutComponent != null) {
            if (targetOutComponent instanceof JTextField) {
                ((JTextField) targetOutComponent).setText(valueAt.toString());
            } else if (targetOutComponent instanceof JButton) {
                ((JButton) targetOutComponent).setText(valueAt.toString());
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private String getFieldText(JComponent field) {
        String fieldText = null;

        if (field instanceof JTextField) {
            fieldText = ((JTextField) field).getText();
        } else if (field instanceof JButton) {
            fieldText = ((JButton) field).getText();
        } else if (field instanceof JComboBox) {
            fieldText = ((JComboBox) field).getSelectedItem().toString();
        } else if (field instanceof JSpinner) {
            JSpinner spinner = (JSpinner) field;
            Date date = (Date) spinner.getValue();
            fieldText = "%";
        }

        return fieldText;
    }

    private String buildWhereCondition() {
        StringBuilder builder = new StringBuilder();

        builder.append(conditionColumns.get(0).toString()).append(" LIKE " + "'").append(getFieldText(fields.get(0))).append("%'");

        for (int i = 1; i < conditionColumns.size(); i++) {
            builder.append(" AND ").append(conditionColumns.get(i)).append(" LIKE " + "'").append(getFieldText(fields.get(i))).append("%'");
        }

        return builder.toString();
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton wyszukajJButton;
    // End of variables declaration//GEN-END:variables

    private void myInitComponents() {

        TableColumnAdjuster tca = new TableColumnAdjuster(jTable1);
        tca.adjustColumns();

        final int fieldWidth = 80;
        final int labelWidth = 80;

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);



        ParallelGroup hParallelGroup = jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING);

        SequentialGroup vSeqGroup = jPanel1Layout.createSequentialGroup();

        for (int i = 0; i < labels.size(); i++) {
            JComponent field = fields.get(i);
            JLabel label = labels.get(i);

            hParallelGroup = hParallelGroup.addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(label, javax.swing.GroupLayout.PREFERRED_SIZE, labelWidth, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(field, javax.swing.GroupLayout.PREFERRED_SIZE, fieldWidth, javax.swing.GroupLayout.PREFERRED_SIZE));

            vSeqGroup = vSeqGroup
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label)
                    .addComponent(field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
        }

        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(hParallelGroup)
                .addContainerGap(27, Short.MAX_VALUE)));

        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(vSeqGroup));
    }
}
